package converter;

import java.util.List;
import javax.faces.component.UIComponent;
import javax.faces.component.UISelectItems;
import javax.faces.component.UISelectOne;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.SelectItem;
import task.TaskCategory;


/**
 *
 * @author Thorsten Ludwig
 */

@FacesConverter(forClass = TaskCategory.class, value="taskCategoryConverter")
public class ExerciseCategoriesConverter implements Converter {

    
    
    
    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String string) {
        UISelectOne listBox = (UISelectOne)uic;
 		// search the UISelectItems list in the ListBox children
 		for (UIComponent child : listBox.getChildren()) {
 			if (child instanceof UISelectItems) {
 				// found it, now get the real SelectItem list
 				UISelectItems items = (UISelectItems)child;
 				List<SelectItem> realitems = (List<SelectItem>) items.getValue();
 				// search for the selected person and return it
 				for (SelectItem item : realitems) {
 					TaskCategory w = (TaskCategory)item.getValue();
 					if ((w!= null) && (w.getName().equals(string))) {
 						// yeah!
 						return w;
 					}
 				}
 			}
 		}
 		throw new AssertionError("DownloadCategory vom Converter nicht gefunden");                
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object o) {
        if (o == null) {
            return "Keine Kategorie";
        } else {
            System.out.println(o);
            return ((TaskCategory) o).getName();
        }
    }
}
